package primetest.impl.manager;

import java.io.IOException;
import java.io.Serializable;

import javax.ejb.Stateful;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpSession;

import primetest.dto.DoctorDto;
import primetest.impl.service.DoctorService;

@Stateful
@Named
@SessionScoped
public class SessionManager implements Serializable{

	/**
	 *
	 */
	private static final long serialVersionUID = -7594833796034520517L;

	@Inject
	private DoctorService doctorService;

	private DoctorDto doctor = null;


	public DoctorDto getLoginUser() throws IOException {
		if(doctor == null){
			ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
			doctor = doctorService.findDoctorById(externalContext.getUserPrincipal().getName());
		}
		return doctor;
	}


	public boolean hasUserRole(String role){
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		return externalContext.isUserInRole(role);
	}


	public void logoff() {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		HttpSession session = (HttpSession)externalContext.getSession(false);
		if(session != null){
			session.invalidate();
		}
	}


	public void redirect(String url)  throws IOException {
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		externalContext.redirect(url);
	}


	public void addGlobalMessageFatal(String summary, String detail){
		FacesContext facesContext = FacesContext.getCurrentInstance();
		facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, summary, detail));
	}


	public void addGlobalMessageWarn(String summary, String detail){
		FacesContext facesContext = FacesContext.getCurrentInstance();
		facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, summary, detail));
	}


	public void addGlobalMessageInfo(String summary, String detail){
		FacesContext facesContext = FacesContext.getCurrentInstance();
		facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, summary, detail));
	}
}
